import React from 'react';
import JSXGraph from 'jsxgraph';
import {Row, Col, Slider, Button, Switch, Input} from 'antd';
import uiStore from '../store/uiStore';

import type1 from '../images/type_1.png';
import type2 from '../images/type_2.png';
import type3 from '../images/type_3.png';
import type4 from '../images/type_4.png';

const marks = {
  0: '0°C',
  25: '25°C',
  50: '50°C',
  75: '75°C',
  100: '100°C',
};

export  default class Curve extends React.Component {
  constructor(props) {
    super(props);

    console.log("curve constructor");
    this.state = {
      board: null,
      curve: null,
      points: [],
      lines: [],
      height: 15,
      width: 15,
      bend: 40
    };
  }

  componentDidMount() {
    console.log("curve component did mount");
    this.draw();
  }

  draw() {
    const {setWidth, setHeight, zoomIn, zoomOut, generateModel, update3Dmodel} = uiStore;

    this.board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-15, 15, 1, -1], keepaspectratio: true,
                                                   axis: true, showCopyright:false,
                                                   showNavigation: false });

    /* var xAxis = this.board.create('axis', [[0,0],[-10,0]], {
     *   firstArrow: false,
     *   lastArrow: true,
     *   ticks: {
     *     drawZero: true,
     *     insertTicks: false,
     *     ticksDistance: 1,
     *     drawLabels: true,
     *     minorTicks: 0,
     *     tickEndings: [1,1]
     *   }
     * });

     * var yAxis = this.board.create('axis', [[0,0],[0,10]], {
     *   firstArrow: false,
     *   lastArrow: true,
     *   ticks: {
     *     drawZero: true,
     *     insertTicks: false,
     *     ticksDistance: 1,
     *     Drawlabels: true,
     *     minorTicks: 0,
     *     tickEndings: [1,1]
     *   }
     * });
     */

    uiStore._setHeight = (height) => {
      var bbox = this.board.getBoundingBox();
      bbox[1] = height;
      this.board.setBoundingBox(bbox);
    };

    uiStore._setWidth = (width) => {
      var bbox = this.board.getBoundingBox();
      bbox[0] = -1 * width;
      this.board.setBoundingBox(bbox);
    };

    uiStore._zoomIn = () => {
      this.board.zoomIn(0, 0);
      var bbox = this.board.getBoundingBox();
      this.setState({height: bbox[1], width: bbox[0]*-1});
    };
    uiStore._zoomOut = () => {
      this.board.zoomOut(0, 0);
      var bbox = this.board.getBoundingBox();
      this.setState({height: bbox[1], width: bbox[0]*-1});
    };

    var p = [];
    var l = [];

    this.board.suspendUpdate();
    var col = 'red';
    p.push(this.board.create('point',[0,9],{strokeColor:col,fillColor:col}));        // data point

    col = 'blue';
    p.push(this.board.create('point',[-1,7],{strokeColor:col,fillColor:col, name:''}));   // control point
    p.push(this.board.create('point',[-2,10],{strokeColor:col,fillColor:col, name:''}));   // control point

    col = 'red';
    p.push(this.board.create('point',[-2,8],{strokeColor:col,fillColor:col}));       // data point
    col = 'blue';
    p.push(this.board.create('point',[-1,6],{strokeColor:col,fillColor:col, name:''}));   // control point
    p.push(this.board.create('point',[-3,8],{strokeColor:col,fillColor:col, name:''}));   // control point

    col = 'red';
    p.push(this.board.create('point',[-3,6],{strokeColor:col,fillColor:col}));       // data point
    col = 'blue';
    p.push(this.board.create('point',[-6,8],{strokeColor:col,fillColor:col, name:''}));   // control point
    p.push(this.board.create('point',[-5,5],{strokeColor:col,fillColor:col, name:''}));   // control point

    col = 'red';
    p.push(this.board.create('point',[-2,4],{strokeColor:col,fillColor:col}));       // data point
    col = 'blue';
    p.push(this.board.create('point',[-1,2],{strokeColor:col,fillColor:col, name:''}));   // control point
    p.push(this.board.create('point',[-7,4],{strokeColor:col,fillColor:col, name:''}));   // control point

    col = 'red';
    p.push(this.board.create('point',[-3,2],{strokeColor:col,fillColor:col}));       // data point
    col = 'blue';
    p.push(this.board.create('point',[-1,1],{strokeColor:col,fillColor:col, name:''}));   // control point
    p.push(this.board.create('point',[-11,2],{strokeColor:col,fillColor:col, name:''}));   // control point

    col = 'red';
    p.push(this.board.create('point',[-4,0],{strokeColor:col,fillColor:col}));       // data point

    l.push(this.board.create('segment',[p[0],p[1]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[3],p[2]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[3],p[4]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[6],p[5]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[6],p[7]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[9],p[8]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[9],p[10]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[12],p[11]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[12],p[13]],{strokeOpacity:0.5}));
    l.push(this.board.create('segment',[p[15],p[14]],{strokeOpacity:0.5}));

    this.curve = this.board.create('curve', JXG.Math.Numerics.bezier(p), {strokecolor:'blue', strokeOpacity:0.6, strokeWidth:5});
    this.board.unsuspendUpdate();

    this.points = p;
    this.lines = l;
    localStorage.setItem('points', JSON.stringify(this.getPointsXY()));

    p.forEach(function(ele){
      ele.on('mouseup', (e)=> {
        let points = JSON.parse(localStorage.getItem('points'));
        for (var i=0;i<points.length;i++) {
          if (ele.id === points[i].id) {
            points[i].x = Math.round(ele.X());
            points[i].y = Math.round(ele.Y());
            break;
          }
        }
        localStorage.setItem('points', JSON.stringify(points));
        generateModel();
      });
    });
  }

  addPoint() {
    console.log("add point");
    console.log(this.points);
    /* this.board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-20, 20, 1, -1], keepaspectratio: true,
     *                                                axis: true, showCopyright:false,
     *                                                showNavigation: false });
     * this.board.update();*/
    this.board.suspendUpdate();
    this.board.removeObject(this.curve);
    // 最后一个点
    let lastIndex = this.points.length - 1;
    let col = 'blue';
    this.points.push(this.board.create('point',[this.points[lastIndex].X() + 2,this.points[lastIndex].Y() + 2],{strokeColor:col,fillColor:col, name:''}));   // control point
    this.points.push(this.board.create('point',[this.points[lastIndex].X() - 2,this.points[lastIndex].Y() - 2],{strokeColor:col,fillColor:col, name:''}));   // control point

    col = 'red';
    this.points.push(this.board.create('point',[this.points[lastIndex].X() - 4,this.points[lastIndex].Y() - 4],{strokeColor:col,fillColor:col}));       // data point

    this.lines.push(this.board.create('segment',[this.points[lastIndex],this.points[lastIndex+1]],{strokeOpacity:0.5}));
    this.lines.push(this.board.create('segment',[this.points[lastIndex+3],this.points[lastIndex+2]],{strokeOpacity:0.5}));

    this.curve = this.board.create('curve', JXG.Math.Numerics.bezier(this.points), {strokecolor:'blue', strokeOpacity:0.6, strokeWidth:5});
    this.board.unsuspendUpdate();

  }

  deletePoint() {
    console.log("delete point");
    this.board.suspendUpdate();
    this.board.removeObject(this.curve);
    this.board.removeObject(this.lines.pop());
    this.board.removeObject(this.lines.pop());
    this.board.removeObject(this.points.pop());
    this.board.removeObject(this.points.pop());
    this.board.removeObject(this.points.pop());

    this.curve = this.board.create('curve', JXG.Math.Numerics.bezier(this.points), {strokecolor:'blue', strokeOpacity:0.6, strokeWidth:5});
    this.board.unsuspendUpdate();
  }

  getPointsXY() {
    let pointsXY = [];
    for (var i=0; i<this.points.length; i++) {
      if (i % 3 == 0) {
        pointsXY.push({id: this.points[i].id ,
                       x: Math.round(this.points[i].X()),
                       y: Math.round(this.points[i].Y())});
      }
    }

    return pointsXY;
  }

  render() {

    console.log("curve render");
    const height = this.state.height;
    const width = this.state.width;
    const bend = this.state.bend;
    const {setWidth, setHeight, zoomIn, zoomOut, generateModel} = uiStore;

    if (this.board) {
      setWidth(width);
      setHeight(height);
    }

    return (
      <div>
        <Row>
          <Col>
            <div id="jxgbox" className="jxgbox" style={{width: 500, height: 500}}></div>
          </Col>
        </Row>

        <br />
        <Row type="flex" align="bottom">
          <Col span={7}><span>Height (mm)</span></Col>
          <Col span={6}></Col>
          <Col span={7}><span>Width (mm)</span></Col>
        </Row>
        <Row type="flex" align="middle">
          <Col span={4}><Input placeholder="Height (mm)" value={height}/></Col>
          <Col span={5}>
            <span>&nbsp;</span>
            <Button onClick={(e) => this.setState(Object.assign({}, this.state, {height: height+1}))}
              type="ghost" shape="circle" size="small" icon="plus" />
            <Button onClick={(e) => this.setState(Object.assign({}, this.state, {height: height-1}))}
              type="ghost" shape="circle" size="small" icon="minus" />
          </Col>
          <Col span={4}></Col>
          <Col span={4}><Input placeholder="Width (mm)" value={width}/></Col>
          <Col span={5}>
            <span>&nbsp;</span>
            <Button onClick={(e) => this.setState(Object.assign({}, this.state, {width: width+1}))}
              type="ghost" shape="circle" size="small" icon="plus" />
            <Button onClick={(e) => this.setState(Object.assign({}, this.state, {width: width-1}))}
              type="ghost" shape="circle" size="small" icon="minus" />
          </Col>
        </Row>
        <br />
        <Row type="flex" justify="space-between" align="middle">
          <Col span={3}>
            <Button
              onClick={(e) => this.setState(Object.assign({}, this.state, {bend: bend-1}))}
              type="ghost" shape="circle" icon="minus" />
          </Col>
          <Col span={16}>
            <Slider marks={marks} value={bend}
              onChange={(v) => this.setState(Object.assign({}, this.state, {bend: v}))} />
          </Col>
          <Col span={3}>
            <Button
              onClick={(e) => this.setState(Object.assign({}, this.state, {bend: bend+1}))}
              type="ghost" shape="circle" icon="plus" />
          </Col>
          <Col span={2}><span>Bend</span></Col>
        </Row>
        <br />
        <Row type="flex" justify="center" align="middle">
          <Col span={3}>
            <Button type="primary" onClick={() => this.addPoint()} icon="plus" />
          </Col>
          <Col span={3}>
            <Button type="primary" onClick={() => this.deletePoint()} icon="minus" />
          </Col>
          <Col span={2}><span>Point</span></Col>
          <Col span={8}></Col>
          <Col span={3}>
            <Button onClick={() => zoomOut()} type="ghost" shape="circle" icon="minus" />
          </Col>
          <Col span={3}>
            <Button onClick={() => zoomIn()} type="ghost" shape="circle" icon="plus" />
          </Col>
          <Col span={2}><span>Zoom</span></Col>
        </Row>
      </div>
    );
  }
}
